using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp;
using Volo.Abp.Modularity;
using Volo.Abp.Uow;

namespace Matrix.ServiceDiscovery
{
    public abstract class MatrixServiceDiscoveryTestBase : AbpIntegratedTest<MatrixServiceDiscoveryTestModule>
    {
        protected override void SetAbpApplicationCreationOptions(AbpApplicationCreationOptions options)
        {
            options.UseAutofac();
        }

        protected virtual Task WithUnitOfWorkAsync(Func<Task> func)
        {
            return WithUnitOfWorkAsync(new AbpUnitOfWorkOptions(), func);
        }

        protected virtual async Task WithUnitOfWorkAsync(AbpUnitOfWorkOptions options, Func<Task> action)
        {
            using var scope = ServiceProvider.CreateScope();
            var uowManager = scope.ServiceProvider.GetRequiredService<IUnitOfWorkManager>();

            using var uow = uowManager.Begin(options);
            await action();
            await uow.CompleteAsync();
        }

        protected virtual Task<T> WithUnitOfWorkAsync<T>(Func<Task<T>> func)
        {
            return WithUnitOfWorkAsync(new AbpUnitOfWorkOptions(), func);
        }

        protected virtual async Task<T> WithUnitOfWorkAsync<T>(AbpUnitOfWorkOptions options, Func<Task<T>> func)
        {
            using var scope = ServiceProvider.CreateScope();
            var uowManager = scope.ServiceProvider.GetRequiredService<IUnitOfWorkManager>();

            using var uow = uowManager.Begin(options);
            var result = await func();
            await uow.CompleteAsync();
            return result;
        }
    }
}